//
//  ChainCollectedVC.m
//  Chain
//
//  Created by zhaosh on 2018/4/16.
//  Copyright © 2018年 zhaosh. All rights reserved.
//

#import "ChainCollectedVC.h"
#import "ChainNoDataView.h"
#import "ChainNewsInfo.h"
#import "ChainNewsCell.h"
#import "MJRefreshBackStateFooter.h"
#import "ChainNormalRefreshHeader.h"
#import "ChainNewsListModel.h"
#import "ChainNewsDetailVC.h"
#import "ChainNormalRefreshFooter.h"
#import "ChainAccountManager.h"
#import "ChainLoginVC.h"

@interface ChainCollectedVC ()<UITableViewDelegate,UITableViewDataSource,ChainNewsCellSelectDelegate>{
    NSInteger _pageNum;
}
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) UITableView *tableview;
@property (strong,nonatomic) UIView *showNoDataView;
@property (assign,nonatomic) BOOL ifEdit;
@property (strong,nonatomic) UIView *bottomView;
@property (strong,nonatomic) UIButton *sureButton;
@end

@implementation ChainCollectedVC

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(CGFLOAT_MIN * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        UIViewController *vc = [self.navigationController.viewControllers lastObject];
        if (vc.fd_prefersNavigationBarHidden) {
            [self.navigationController setNavigationBarHidden:YES animated:NO];
        } else {
            [self.navigationController setNavigationBarHidden:NO animated:NO];
        }
    });
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
     [self setHeadView:self.view withLeftBtnText:@"chainBack" withHeadLable:@"我的收藏" withRightBntText:@"编辑"];
    
    self.view.backgroundColor =[UIColor whiteColor];
    [self setupTableview];
    
    [self getNewData];
}

-(void)setupErrorView{
    self.noDataView = [[ChainNoDataView alloc]initWithFrame:self.tableview.bounds];
        
    self.noDataView.hidden = YES;
    [self.tableview addSubview:self.noDataView];
}

-(void)fetchListDataWithPage:(NSUInteger)pageNum{
    NSString *requestPage =[NSString stringWithFormat:@"%ld",_pageNum];
    NSDictionary *params = @{@"pageNum":requestPage,@"pageSize":@"10"};
    NSString *requestUrl=[NSString stringWithFormat:@"%@%@",BASE_URL,@"/latoutiao/news/collectedNewsList"];
     __weak typeof(self) weakSelf = self;
    
    [[ChainNetAPIClient sharedJsonClient]postRequestJsonDataWithPath:requestUrl withParams:params withHeader:nil andBlock:^(id data, NSError *error) {
        [self hideHUDafterDelay:0];
        
        NSDictionary *info = [NSDictionary dictionaryWithDictionary:data];
        if (error) {
            NSString *message=[info objectForKey:@"message"];
            [MBProgressHUD  showMessage:message ToView:nil RemainTime:0.5];
        }else{
            NSString *status=[NSString stringWithFormat:@"%@",[info objectForKey:@"status"]];
            NSString *errorCode=[NSString stringWithFormat:@"%@",[info objectForKey:@"errorCode"]];
            if ([status isEqualToString:@"OK"]) {
                if (_pageNum==1) {
                    [weakSelf.dataArray removeAllObjects];
                }
                NSArray *tempArray=[data valueForKeyPath:@"entityList"];
                
                for (NSDictionary *dic in tempArray) {
                    ChainNewsListModel *info = [ChainNewsListModel yy_modelWithDictionary:dic];
                    [weakSelf.dataArray addObject:info];
                }
            }else{
                if ([errorCode isEqualToString:@"0"]) {
                    [ChainAccountManager removeAccountCache];
                    [weakSelf pushLoginVC];
                }
            }
        }
        
        weakSelf.noDataView.hidden = weakSelf.dataArray.count != 0;
        
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        
        [weakSelf.tableview reloadData];
    }];
}

-(void)setupTableview{
    self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, kTopHeight, ScreenWidth, ScreenHeight-kTopHeight) style:UITableViewStylePlain];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.backgroundColor = AllViewBackgroundColor;
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableview];
    
    //ios11有向上抖动问题
    NSString *version = [UIDevice currentDevice].systemVersion;
    if (version.doubleValue >= 11.0) {
        self.tableview.estimatedRowHeight = 0;
        self.tableview.estimatedSectionFooterHeight = 0;
        self.tableview.estimatedSectionHeaderHeight = 0;
        self.tableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    __weak typeof(self) weakSelf = self;
    //添加顶部下啦刷新视图
    self.tableview.mj_header = [ChainNormalRefreshHeader headerWithRefreshingBlock:^{
        [weakSelf getNewData];
    }];
    //添加底部上提加载视图
    self.tableview.mj_footer = [ChainNormalRefreshFooter footerWithRefreshingBlock:^{
        [weakSelf getNextData];
    }];
    [self setupErrorView];
}

-(void)pushLoginVC{
    ChainLoginVC *loginVC=[[ChainLoginVC alloc] init];
    [self.navigationController pushViewController:loginVC animated:NO];
}

-(void)getNewData{
    _pageNum = 1;
    
    [self showLoading];
    [self fetchListDataWithPage:_pageNum];
}

-(void)getNextData{
    _pageNum++;
    [self fetchListDataWithPage:_pageNum];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ChainNewsCell *cell = [ChainNewsCell cellWithTableView:tableView];
    cell.delegate=self;
    cell.item = self.dataArray[indexPath.row];
    return cell;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleNone;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ChainNewsListModel *info = self.dataArray[indexPath.row];
    
    ChainNewsCell *cell = [ChainNewsCell cellWithTableView:tableView];
    cell.item = info;
    [cell layoutSubviews];

    CGFloat rowH = cell.item.rowHeight;
    cell = nil;
    return rowH;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ChainNewsListModel *info = self.dataArray[indexPath.row];
    
    ChainNewsDetailVC *detailVC =[[ChainNewsDetailVC alloc] init];
    detailVC.detailId = info._id;
    [self.navigationController pushViewController:detailVC animated:YES];
}

-(void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)addAction{
    if (_ifEdit==NO) {
        [self createBottomView];
        
        _ifEdit=YES;
        [self.rightBtn setTitle:@"取消" forState:UIControlStateNormal];
        [self.tableview setEditing:YES];
        
        for (int i=0; i<[self.dataArray count]; i++) {
            ChainNewsListModel *model = [self.dataArray objectAtIndex:i];
            model.isEdit=YES;
            if ([model.isSelected  isEqualToString:@"1"]) {
                model.isSelected =@"0";
            }
        }
    }else{
        [self.bottomView removeFromSuperview];
        _ifEdit=NO;
        [self.tableview setEditing:NO];
        for (int i=0; i<[self.dataArray count]; i++) {
            ChainNewsListModel *model = [self.dataArray objectAtIndex:i];
            model.isEdit=NO;
        }
        [self.rightBtn setTitle:@"编辑" forState:UIControlStateNormal];
    }
    [self.tableview reloadData];
}

-(void)doSelectRow:(ChainNewsListModel *)model{
    
}

-(void)createBottomView{
    self.bottomView=[[UIView alloc] initWithFrame:CGRectMake(0, self.view.height-60, self.view.width, 60)];
    self.bottomView.backgroundColor=[UIColor whiteColor];
    
    UIView *lineView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 0.5)];
    lineView.backgroundColor =[UIColor colorWithHexString:@"#d9d9d9"];
    [self.bottomView addSubview:lineView];
    
    self.sureButton=[[UIButton alloc] initWithFrame:CGRectMake(30, 10, self.view.width-60, 40)];
    [self.sureButton setBackgroundColor:[UIColor clearColor]];
    [self.sureButton setTitleColor:[UIColor colorWithHexString:@"cccccc"] forState:UIControlStateNormal];
    self.sureButton.titleLabel.font=[UIFont boldSystemFontOfSize:16];
    [self.sureButton setTitle:@"删除" forState:UIControlStateNormal];
    [self.sureButton addTarget:self action:@selector(doTouchDeleteCollectBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:self.sureButton];
    
    [self.view addSubview:self.bottomView];
}

-(void)touchCheckBtn:(ChainNewsListModel *)model{
    NSMutableArray *collectedIdList=[NSMutableArray array];
    for (int i=0; i<[self.dataArray count]; i++) {
        ChainNewsListModel *model = [self.dataArray objectAtIndex:i];
          if ([model.isSelected isEqualToString:@"1"]) {
            [collectedIdList addObject:model._id];
        }
    }
    
    if (collectedIdList.count==0) {
          [self.sureButton setTitle:@"删除" forState:UIControlStateNormal];
        [self.sureButton setTitleColor:[UIColor colorWithHexString:@"cccccc"] forState:UIControlStateNormal];
    }else{
        NSString *titleStr = [NSString stringWithFormat:@"删除(%d)",collectedIdList.count];
        [self.sureButton setTitle:titleStr forState:UIControlStateNormal];
        [self.sureButton setTitleColor:[UIColor colorWithHexString:@"ce0d0d"] forState:UIControlStateNormal];
    }
}


-(void)doTouchDeleteCollectBtn:(UIButton *)btn{
    UIAlertView *alterView=[[UIAlertView alloc] initWithTitle:nil message:@"确认删除选项" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认",nil];
    [alterView show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==1) {
        NSMutableArray *collectedIdList=[NSMutableArray array];
        for (int i=0; i<[self.dataArray count]; i++) {
            ChainNewsListModel *model = [self.dataArray objectAtIndex:i];
            if ([model.isSelected isEqualToString:@"1"]) {
               [collectedIdList addObject:model._id];
            }
        }
        __weak typeof(self) weakSelf=self;
        NSDictionary *param=[NSDictionary dictionaryWithObjectsAndKeys:collectedIdList,@"collectedIdList",nil];
        NSString *requestUrl=[NSString stringWithFormat:@"%@%@",BASE_URL,@"/latoutiao/news/deleteCollectedNews"];
        [[ChainNetAPIClient sharedJsonClient]postRequestJsonDataWithPath:requestUrl withParams:param withHeader:nil andBlock:^(id data, NSError *error) {
            [self hideHUDafterDelay:0];
            
            NSDictionary *info = [NSDictionary dictionaryWithDictionary:data];
            if (error) {
                NSString *message=[info objectForKey:@"message"];
                [MBProgressHUD  showMessage:message ToView:nil RemainTime:0.5];
            }else{
                NSString *status=[NSString stringWithFormat:@"%@",[info objectForKey:@"status"]];
                NSString *errorCode=[NSString stringWithFormat:@"%@",[info objectForKey:@"errorCode"]];
                if ([status isEqualToString:@"OK"]) {
                    [weakSelf.bottomView removeFromSuperview];
                    weakSelf.ifEdit=NO;
                    [weakSelf.tableview setEditing:NO];
                    [weakSelf.rightBtn setTitle:@"编辑" forState:UIControlStateNormal];
                }else{
                    if ([errorCode isEqualToString:@"0"]) {
                        [ChainAccountManager removeAccountCache];
                        [weakSelf pushLoginVC];
                    }
                }
            }
           [weakSelf getNewData];
        }];
    }
}
@end
